package cn.fl.project.prjfile.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.bcel.generic.I2F;
import org.apache.bcel.generic.IF_ACMPEQ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.constant.UploadConstant;
import cmm.comm.facade.upload.dto.SysUlDatCfgDTO;
import cmm.comm.facade.upload.dto.SysUlDatCfgDtlDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapPayInfoDTO;
import cn.fl.capital.vo.CapPayMaterialVo;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.prjfile.api.IPrjFilesRecApiService;
import cn.fl.prjfile.condition.PrjFilesRecQueryCondition;
import cn.fl.prjfile.constant.PrjFilesRecConstant;
import cn.fl.prjfile.dto.PrjFilesRecDTO;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.prjfile.service.IPrjFilesRecService;
import cn.fl.project.prjfile.transform.PrjFilesRecVOTransform;
import cn.fl.project.prjfile.vo.PrjFilesRecVO;
import cn.fl.system.constant.SysLogConstant;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.warrant.facade.archive.constant.ArchiveConstants;

/**
 * @Description: PRJ_FILES_REC项目补充资料表 服务层接口实现
 */
@Service
public class PrjFilesRecServiceImpl implements IPrjFilesRecService {
	
	private static final Logger logger = LoggerFactory.getLogger(PrjFilesRecServiceImpl.class);
	
	/**
	 * 文件上传记录表 服务层接口
	 */
	@Autowired
	private IPrjFilesRecApiService prjFilesRecApiService;
	@Autowired
    private IUploadApiService uploadApiService;
	 @Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	 @Autowired
	 private IFlowApiService flowApiService;
	//**************************文件上传记录*********************//

	@Override
	public Long add(PrjFilesRecVO entity) throws BaseException {
		if(null==entity){
			BaseLogUtils.info(logger, "addPrjFilesRec", "新增文件上传记录失败,文件记录对象为空.DATA:"+JSONObject.toJSONString(entity));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "新增文件上传记录失败,文件记录对象不能为空!");
		}
		String sysCd = entity.getSysCd();
		String orgCd = entity.getOrgCd();
		String cfgCd = entity.getCfgCd();
		String cfgDtlCd = entity.getCfgDtlCd();
		
		if(StringUtils.isEmpty(sysCd)){
			BaseLogUtils.info(logger, "addPrjFilesRec", "系统代码不能为空.DATA:"+JSONObject.toJSONString(entity));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "系统代码不能为空!");
		}
		
		if(StringUtils.isEmpty(orgCd)){
			BaseLogUtils.info(logger, "addPrjFilesRec", "组织架构代码不能为空.DATA:"+JSONObject.toJSONString(entity));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "组织架构代码不能为空!");
		}
		
		if(StringUtils.isEmpty(cfgCd)){
			BaseLogUtils.info(logger, "addPrjFilesRec", "配置编号不能为空.DATA:"+JSONObject.toJSONString(entity));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "配置编号不能为空!");
		}
		
		if(StringUtils.isEmpty(cfgDtlCd)){
			BaseLogUtils.info(logger, "addPrjFilesRec", "配置子编码不能为空.DATA:"+JSONObject.toJSONString(entity));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "配置子编码不能为空!");
		}
		
		return this.prjFilesRecApiService.add(PrjFilesRecVOTransform.toDTO(entity));
	}
	
	@Override
	public Boolean addList(List<PrjFilesRecVO> list) throws BaseException {
		if(CollectionUtils.isEmpty(list)){
			return false;
		}
		return this.prjFilesRecApiService.addList(PrjFilesRecVOTransform.toDTOList(list));
	}

	@Override
	public boolean removePrjFilesRecByIds(List<Long> ids)
			throws BaseException {
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removePrjFilesRecByIds", "删除文件上传记录失败,主键参数为空.IDS:"+JSONObject.toJSONString(ids));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "主键集合不能为空!");
		}
		return this.prjFilesRecApiService.removePrjFilesRecByIds(ids);
	}

	@Override
	public List<PrjFilesRecVO> searchList(
			PrjFilesRecQueryCondition condition) throws BaseException {
		
		return PrjFilesRecVOTransform.toVOList(this.prjFilesRecApiService.searchList(condition));
	}

	

	@Override
	public PrjFilesRecVO selectById(Long id) throws BaseException {
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "searchSysUlDatCfgDtlList", "查询文件上传记录失败,缺少必要的查询条件:ID:"+JSONObject.toJSONString(id));
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		PrjFilesRecVO vo = PrjFilesRecVOTransform.toVO(this.prjFilesRecApiService.selectById(id));
		
		return vo;
	}

	@Override
	public boolean removePrjFilesRecByCondition(PrjFilesRecQueryCondition qc) throws BaseException {
		if(null==qc) return false;
		return	this.prjFilesRecApiService.removePrjFilesRecByCondition(qc);
	}

	

	@Override
	public boolean modifyAudStsCd(PrjFilesRecQueryCondition condition) throws BaseException {
		return this.prjFilesRecApiService.modifyAudStsCd(condition);
	}

	@Override
	public boolean modifyAudStsCdById(Long id, String audStsCd) throws BaseException {
		return this.prjFilesRecApiService.modifyAudStsCdById(id, audStsCd);
	}


	@Override
	public Pager searchListPage(Pager page) throws BaseException {
		 if(null == page){
	             throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
	         }
	         return this.prjFilesRecApiService.searchListPage(page);
	}

	
	@Override
	public boolean update(PrjFilesRecVO vo) throws BaseException {
		// TODO Auto-generated method stub
		 return this.prjFilesRecApiService.update(PrjFilesRecVOTransform.toDTO(vo));
	}

	@Override
	public boolean removeById(Long id) throws BaseException {
		// TODO Auto-generated method stub
		return this.prjFilesRecApiService.removeById(id);
	}

	@Override
	public boolean modifyAudStsCdByIdList(List<Long> idList, String audStsCd) throws BaseException {
		// TODO Auto-generated method stub
		return this.prjFilesRecApiService.modifyAudStsCdByIdList(idList, audStsCd);
	}

	@Override
	public boolean modifyIsDelCdById(Long id, String isDel) throws BaseException {
		// TODO Auto-generated method stub
		return this.prjFilesRecApiService.modifyIsDelCdById(id, isDel);
	}

	@Override
	public List<CapPayMaterialVo> searchMateList(PrjFilesRecQueryCondition qc) throws BaseException {
		// TODO Auto-generated method stub
		String sysorg=CapitalConstant.SYSORG;
		List<String> cfgCdList = new ArrayList<>();
		List<PrjFilesRecDTO> blist=this.prjFilesRecApiService.searchList(qc);
		List<String> dataIds = new ArrayList<>();
		dataIds.add(qc.getPkId());
		if (blist==null||blist.size()<1) {
			return null;
		}else {
			sysorg=blist.get(0).getOrgCd();
			for (int i = 0; i < blist.size(); i++) {
				cfgCdList.add(blist.get(i).getCfgCd());
				dataIds.add(blist.get(i).getId().toString());
			}
		}
		//查询放款资料配置，系统代码,组织架构代码,配置编号 ,业务主键
		SysUlDatCfgQueryCondition ulDatCfgQueryCondition = new SysUlDatCfgQueryCondition();
		ulDatCfgQueryCondition.setSysCd(CapitalConstant.SYSCD);
		ulDatCfgQueryCondition.setOrgCd(sysorg);//组织架构代码
		ulDatCfgQueryCondition.setCfgCdList(cfgCdList);//配置编号
		ulDatCfgQueryCondition.setDataIds(dataIds);
		ulDatCfgQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码		
		List<SysUlDatCfgDTO> list = uploadApiService.searchSysUlDatCfgListByDataId(ulDatCfgQueryCondition);
		List<CapPayMaterialVo> voList = null;
		if (CollectionUtils.isNotEmpty(list)) {
			Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_MATE_AUD_STS_CD);
			voList = new ArrayList<>();
			CapPayMaterialVo vo;
			//设置路径
			String picServicePath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
			for (SysUlDatCfgDTO dto : list) {
				for (SysUlDatCfgDtlDTO dtlDTO : dto.getSysUlDatCfgDtlDTOList()) {
					//判断是否要补充
					vo = new CapPayMaterialVo();
					boolean bu=false;
					for (PrjFilesRecDTO file: blist) {
						if (file.getCfgCd().equals(dtlDTO.getCfgCd())
								&&file.getCfgDtlCd().equals(dtlDTO.getCfgDtlCd())) {
							bu=true;
							vo.setId(file.getId());
						}
					}
					if (!bu) {
						continue;
					}
					
					//vo.setId(Long.parseLong(qc.getPkId()));
					vo.setCfgDtlCd(dtlDTO.getCfgDtlCd());//配置子编号
					vo.setDatNm(dtlDTO.getDatNm());//配置名称
					vo.setCfgCd(dtlDTO.getCfgCd());//配置编号
					vo.setCfgNm(dto.getCfgNm());//配置子名称
					vo.setFileId(dtlDTO.getRecId());//附件ID
					//如果有HTTP开头说明是可以访问路径,无需干涉
					if(StringUtils.isNotBlank(dtlDTO.getFilePath())&&!dtlDTO.getFilePath().startsWith("http") && StringUtils.isNotBlank(picServicePath)){
						vo.setFilePath(picServicePath+dtlDTO.getFilePath());
					}else{
						vo.setFilePath(dtlDTO.getFilePath());//附件路径
					}
					vo.setFileNm(dtlDTO.getRecFileNm());//上传名称
					vo.setCrtTm(dtlDTO.getRecCrtTm());//上传时间
					vo.setOrgCd(dtlDTO.getOrgCd());//机构代码
					vo.setSysCd(dtlDTO.getSysCd());//系统代码
					//是否必传
					vo.setIsMust(dtlDTO.getIsMust());
					if (StringUtils.isNotBlank(dtlDTO.getRecAudStsCd())) {
						vo.setAudStsCd(dtlDTO.getRecAudStsCd());//验证状态
					} else {
						vo.setAudStsCd("0");//验证状态
					}

					if (audStsCdMap != null && audStsCdMap.containsKey(vo.getAudStsCd())) {
						vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
					}
					voList.add(vo);
				}
			}
		}
		return voList;
		
	}
	@Override
	public  DataResultDTO addFlowStart(Map map) throws BaseException {
		DataResultDTO result = new DataResultDTO(BaseExceptionConstant.BASE_EXCEPTION_CODE_200,
				SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String id=(String)map.get("id");
		if (StringUtils.isEmpty(id)) {
			result.setCode(BaseExceptionConstant.BASE_EXCEPTION_CODE_405);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "addFlowStart",
					SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY,
					CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			// 流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(PrjBscInfoConstant.PRJ_FLOW_S_H_PRJ);
			flowStartParamsDTO.setProcDefKey(PrjFilesRecConstant.FLOW_MODEL_KEY);
//			flowStartParamsDTO.setProcDefId(procDefId);
//			flowStartParamsDTO.setProcNo(procNo);
//			map.put("currentUser", CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext
					.getCurrentUserId());
			flowStartParamsDTO.setBusinessKey(id);
			flowStartParamsDTO.setIsFlowStatePassCanbeStart(true);
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext
					.getCurrentBuOrgCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext
					.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext
					.getCurrentUserName());
			flowStartParamsDTO
					.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);// 优先级,可以在界面定义
			flowStartParamsDTO
					.setBusinessType(PrjFilesRecConstant.FLOW_MODEL_TYP_F);// TODO
																					// 确认用不用
			flowStartParamsDTO.setModelTyp(PrjFilesRecConstant.FLOW_MODEL_TYP_F);// 需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc((String)map.get("keyword"));
			// flowStartParamsDTO.setOrgShtNm(CurrentThreadContext.getCurrentOrgShtNm());
			//flowStartParamsDTO.setCstNm((String)map.get("cstNm"));
			flowStartParamsDTO.setStartParams(map);
			BaseLogUtils.info(logger, "addFlowStart", "===发起流程Start===参数:" + JSON.toJSONString(flowStartParamsDTO));
            result = this.flowApiService.noTransFlowStart(flowStartParamsDTO);
            BaseLogUtils.info(logger, "addFlowStart", "===发起流程End===结果:" + JSON.toJSONString(result));

			if (null != result && null != result.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) result
						.getData();
				if (StringUtils
						.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:"
							+ flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功");
				}
			}
			
		} catch (BaseException e) {
			result.setCode(BaseExceptionConstant.BASE_EXCEPTION_CODE_405);
			result.setInfo(e.getMessage());
			logger.info(e.getMessage());
		} catch (Exception e) {
			result.setCode(BaseExceptionConstant.BASE_EXCEPTION_CODE_405);
			result.setInfo("系统错误,请联系管理员！");
			logger.error("系统错误,请联系管理员！" + e.getMessage());
		}
		return result;
		
	}
	

}
